package com.xiaokan.utils;

import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class BufferedRandomAccessFile {

	private RandomAccessFile fin;

	private int realBufferSize = 0;

	private int bufSize = 0;

	private int curPos = 0;

	private byte buf[];

	public BufferedRandomAccessFile(String path, int bufSize) throws IOException {
		fin = new RandomAccessFile(path, "r");
		this.bufSize = bufSize;
		buf = new byte[bufSize];
		refillBuffer();
	}

	public BufferedRandomAccessFile(String path) throws IOException {
		this(path, 20 * 1024 * 1024);
	}

	public void seek(long pos) throws IOException {
		fin.seek(pos);
		refillBuffer();
	}

	public byte readByte() throws IOException {
		if (curPos >= realBufferSize) {
			refillBuffer();
			if (realBufferSize <= 0) {
				throw new EOFException();
			}
		}
		return buf[curPos++];
	}

	private void refillBuffer() throws IOException {
		realBufferSize = fin.read(buf, 0, bufSize);
		curPos = 0;
	}

	public void close() throws IOException {
		fin.close();
	}

}
